package net.huashitong.supervision.task.controller;

import com.sirdc.modules.core.exceptions.SystemException;
import com.sirdc.modules.core.exceptions.UserExistException;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.databean.tree.DeptRoomDTO;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysDeptRoom;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysDeptFilter;
import com.sirdc.modules.sys.filter.SysDeptRoomFilter;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.*;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.sys.util.UserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.task.entity.RoomUserEntity;
import net.huashitong.supervision.task.service.RoomUserService;
import net.huashitong.supervision.task.service.UserManageService;
import net.huashitong.supervision.task.util.RoleMenuUtilsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.CollationKey;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/9/10
 * Time: 17:11
 * To change this template use File | Settings | File Templates.
 * Description:用户管理控制层
 */
@Controller
@RequestMapping(value = "/user")
public class UserManageController extends JsonBaseController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private UserManageService userManageService;
    @Autowired
    private RoleMenuUtilsService roleMenuUtilsService;
    @Autowired
    private SysDeptRoomService deptRoomService;
    @Autowired
    private RoomUserService roomUserService;

    @Override
    protected String getView(String s) {
        return "/modules/task/user/" + s;
    }


    /**
     * 返回单位用户列表页面
     *
     * @return
     */
    @RequestMapping(value = "/roomQuery")
    public String showRoomView() {
        return getView("roomQuery");
    }

    /**
     * 请求单位，部门，科室信息树状结构
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deptRoom", method = RequestMethod.GET)
    public Message getDeptRoom(SysDeptRoomFilter filter) {

        List<DeptRoomDTO> treeDeptRoom = deptRoomService.getTreeDeptRoom(filter);

        return coverMessage("200","部门科室树状结构",treeDeptRoom);
    }

    /**
     * 获取用户信息
     * @param sysId
     * @param tree
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDeptRoomUsers", method = RequestMethod.GET)
    public Message getUsers(String sysId, int tree)
    {


        List<SysUserDataBean> list = new ArrayList<>();
        if(1==tree){

//            list = sysLoginService.getByDeptId(sysId);
            SysUserFilter filter = new SysUserFilter();
            filter.setDeptId(sysId);
            list= sysUserService.queryOnDatabeanNoPage(filter);
            list.forEach(o->o.setUserId(o.getSysId()));
        }
        if(2==tree)
        {
            List<RoomUserEntity> userList = roomUserService.getUsersByRoomId(sysId);

            for (RoomUserEntity entity : userList) {
                String userId = entity.getUserId();
                SysUserDataBean bean = sysUserService.getEntityById(userId);
                bean.setUserId(bean.getSysId());
                list.add(bean);

            }
        }

        return coverMessage("200","根据id返回人员",list);


    }


    /**
     * 保存科室人员
     * @param databean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addUsers", method = RequestMethod.POST)
    public Message createUser(@RequestBody SysUserDataBean databean)
    {
//        SysUserDataBean databean = new SysUserDataBean();
        if(StringUtils.isBlank(databean.getRoomId())&&2==databean.getTree())
        {
            return  coverMessage("500","科室Id不能为空");
        }

        SysLogin sysLogin = sysUserService.saveUserLogin(databean);//保存用户信息；
//        保存单位或者科室关联信息
        int tree = databean.getTree();
        if(2==tree)//增加科室信息
        {
            RoomUserEntity roomUser = new RoomUserEntity();
            roomUser.setUserId(sysLogin.getSysId());
            roomUser.setValid(1);
            roomUser.setRoomId(databean.getRoomId());
            RoomUserEntity isExit = roomUserService.getUserByRoomIdAndUserId(databean.getRoomId(), sysLogin.getSysId());
            if(isExit==null)
            {
                roomUserService.save(roomUser);
            }
        }

        return  coverMessage("200","保存成功");

    }

    /**
     * 修改用户             ;
     */
    @ResponseBody
    @RequestMapping(value = "/updUsers", method = RequestMethod.POST)
    public Message updUsers(@RequestBody SysUserDataBean databean)
    {
        if(StringUtils.isNotBlank(databean.getUserId()))
        {

            sysUserService.updateUserLogin(databean);
            return coverMessage("200","操作成功");
        }else {
            return coverMessage("500", "操作失败,用户id不能为空");
        }

    }

    /**
     * 重置密码
     */
    @ResponseBody
    @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
    public Message resetPwd(@RequestBody SysUserDataBean databean)
    {
        if(StringUtils.isBlank(databean.getUserId()))
        {

            return coverMessage("500", "操作失败");
        }else {
            SysUserDataBean updBean = new SysUserDataBean();
            updBean.setUserId(databean.getUserId());
            updBean.setPassword("123456");
            sysLoginService.updatePassword(updBean);
            return coverMessage("200","操作成功，密码已重置为：123456");
        }

    }


    /**
     * 添加到其他科室
     */
    @ResponseBody
    @RequestMapping(value = "/addToRoom", method = RequestMethod.POST)
    public Message addToOtherRoom(@RequestBody SysUserDataBean dataBean)
    {
        if (StringUtils.isBlank(dataBean.getRoomId())||StringUtils.isBlank(dataBean.getUserId())) {
            return coverMessage("500","请先选择科室");
        }


        String[] roomIds = dataBean.getRoomId().split(",");
        for (String roomId : roomIds) {

            RoomUserEntity roomUser = new RoomUserEntity();
            roomUser.setUserId(dataBean.getUserId());
            roomUser.setValid(1);
            roomUser.setRoomId(roomId);
            RoomUserEntity isExit = roomUserService.getUserByRoomIdAndUserId(roomId, dataBean.getUserId());
            if(isExit==null)
            {
                roomUserService.save(roomUser);
            }else {
//                return coverMessage("500","已经存在该科室，不可重复添加");
                System.out.println("忽略："+dataBean.getUserId());
            }
        }

        return coverMessage("200","操作成功");
    }
    /**
     * 删除人员所在的科室
     */
    @ResponseBody
    @RequestMapping(value = "/delUserRoom", method = RequestMethod.POST)
    public Message delete(@RequestBody SysUserDataBean dataBean)
    {
        if (StringUtils.isBlank(dataBean.getRoomId())||StringUtils.isBlank(dataBean.getUserId())) {
            return coverMessage("500","请先选择科室");
        }
        RoomUserEntity entity = roomUserService.getUserByRoomIdAndUserId(dataBean.getRoomId(), dataBean.getUserId());
        if(entity!=null)
        {

            roomUserService.deleteById(entity.getSysId());
        }else {
            return coverMessage("500","操作失败");
        }
        return  coverMessage("200","操作成功");

    }

    /**
     * 新增科室
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addNewRoom", method = RequestMethod.POST)
    public Message addNewRoom(@RequestBody SysDeptRoomFilter filter)
    {

        deptRoomService.createDeptRoom(filter);
        return  coverMessage("200","操作成功");

    }

    /**
     * 删除科室
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delRooms", method = RequestMethod.POST)
    public Message delRooms(@RequestBody SysDeptRoomFilter filter)
    {

        List<String> ids = filter.getIds();
        if(ObjectUtils.isBlank(ids))
        {
            return coverMessage("500","请先选择科室");
        }
        for (String id : ids) {

            deptRoomService.deleteById(id);
        }

        return  coverMessage("200","操作成功");

    }

    /**
     * 获取分管领导
     */
    @ResponseBody
    @RequestMapping(value = "/getgfleaders", method = RequestMethod.GET)
    public  Message getFGleader(String deptId){

       // String deptId = SysUserUtils.getDeptId();
        String userId  = SysUserUtils.getUserId();
        List<SysUserDataBean> fgleaders= new ArrayList<>();
        if(StringUtils.isBlank(deptId))
        {
            return  coverMessage("500","登陆超时",fgleaders);

        }
        List<SysUserDataBean> byDeptId = sysLoginService.getFgLeader();
        if("admin".equals(userId)){

            fgleaders= byDeptId.stream().filter(obj -> ("03").equals(obj.getRoleId())).collect(Collectors.toList());
        }else {
            fgleaders= byDeptId.stream().filter(obj -> ("03").equals(obj.getRoleId())&&deptId.equals(obj.getDeptId())).collect(Collectors.toList());

        }

        //名字首字母排序
        Collections.sort(fgleaders, new Comparator<SysUserDataBean>() {
            Collator collator = Collator.getInstance(Locale.CHINA);
            @Override
            public int compare(SysUserDataBean o1, SysUserDataBean o2) {
                CollationKey key1 = collator.getCollationKey(o1.getName());
                CollationKey key2 = collator.getCollationKey(o2.getName());
                return key1.compareTo(key2);
            }
        });

        return  coverMessage("200","获取分管领导成功",fgleaders);
    }

    /**
     * 修改单位或者科室的基本信息
     */
    @ResponseBody
    @RequestMapping(value = "/updDeptRoom", method = RequestMethod.POST)
    public Message updDeptRoom(@RequestBody SysDeptRoomFilter filter)
    {
        if(StringUtils.isBlank(filter.getSysId()))
        {
            return coverMessage("500", "操作失败，参数错误");
        }
        String sysId = filter.getSysId();
        String orderBy = filter.getOrderBy();
        String state = filter.getState();
        String name = filter.getName();
        String fgLeader = filter.getFgLeader();
        if(filter.getTree()==1){
            //修改单位信息
            SysDept dept = sysDeptService.getById(sysId);
            dept.setDeptName(name);
            dept.setState(state);
            dept.setOrderBy(Integer.parseInt(orderBy));
            sysDeptService.update(dept);

        }else if(2==filter.getTree())
        {
            SysDeptRoom room = deptRoomService.getById(sysId);
            room.setRoomName(name);
            room.setOrderBy(orderBy);
            room.setState(state);
            room.setFgLeader(fgLeader);
            deptRoomService.update(room);
        }

        return coverMessage("200","操作成功");
    }
    /**
     * 搜索
     */
    @ResponseBody
    @RequestMapping(value = "/serchData", method = RequestMethod.GET)
    public Message updDeptRoom(String keyWords,HttpServletRequest request ){

        /*String   keyWords="";
        try {
               keyWords = new String(request.getParameter("keyWords").getBytes("iso8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return coverMessage("500","请输入关键字");

        }*/

        if(StringUtils.isBlank(keyWords))
        {
            return coverMessage("500","请输入关键字");
        }

        List<DeptRoomDTO> byKeyWords = deptRoomService.getByKeyWords(keyWords);


        return coverMessage("200","根据关键字搜索",byKeyWords);


    }
    /**
     * 返回单位用户列表页面
     *
     * @return
     */
    @RequestMapping(value = "/query")
    public String showUserList() {
        return getView("query");
    }

    /**
     * 查询
     *
     * @return
     */
    @RequestMapping(value = "/filter")
    public String filter() {
        return getView("filter");
    }

    /**
     * 单位用户列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid showUserList(SysUserFilter filter) {
        List<SysUser> userList = userManageService.queryFilter(filter);
        return coverJqGrid(filter, userList);
    }

    /**
     * 打开添加用户页面
     *
     * @return
     */
    @RequestMapping(value = "/create")
    public String addUser(@ModelAttribute SysUserDataBean datebean, Model model) {
        String deptId = SysUserUtils.getDeptId();
        datebean.setDeptId(deptId);
        model.addAttribute("datebean", datebean);
        return getView("form");
    }

    /**
     * 添加本单位用户
     *
     * @param userDataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Message addUser(SysUserDataBean userDataBean) {
        if (StringUtils.isNotBlank(SysUserUtils.getUserId())) {
            userDataBean.setDeptId(SysUserUtils.getDeptId());
            try {
                userManageService.addUser(userDataBean);
            } catch (UserExistException ue) {
                return coverMessage("500", ue.getMessage() + "该用户名其他单位存在");
            } catch (NullPointerException e) {
                return coverMessage("500", "登录超时，请重新登录");
            } catch (SystemException se) {
                return coverMessage("500", se.getMessage());
            }
            return coverMessage("200");
        } else {
            return coverMessage("登录超时，请重新登录");
        }
    }

    /**
     * 用户导入
     *
     * @param excelFile
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/userExcel", method = RequestMethod.POST)
    public String userExcel(@RequestParam MultipartFile excelFile, HttpServletResponse response) throws IOException {
        if (StringUtils.isNotBlank(SysUserUtils.getDeptId())) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            Map<String, Object> map = new HashMap<String, Object>();
            String name = excelFile.getOriginalFilename();
            if (!name.endsWith(".xls") && !name.endsWith(".xlsx")) {
                System.out.println("文件不是excel类型");
                return "文件类型错误";
            } else {
                String s = null;
                try {
                    s = userManageService.createUserExcel(excelFile.getInputStream(), name);
                } catch (UserExistException ue) {
                    return "【" + ue.getMessage() + "】该用户名其他单位已存在，请修改用户名";
                } catch (SystemException se) {
                    return se.getMessage();
                }
                if ("200".equals(s)) {
                    return "导入Excel成功";
                } else {
                    return s;
                }
            }
        } else {
            return "登录超时，请重新登录";
        }
    }


    /**
     * 单位公用账号导表
     *
     * @param excelFile
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/deptUserExcel", method = RequestMethod.POST)
    public String deptUserExcel(@RequestParam MultipartFile excelFile, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        String name = excelFile.getOriginalFilename();
        if (!name.endsWith(".xls") && !name.endsWith(".xlsx")) {
            System.out.println("文件不是excel类型");
            return "文件类型错误";
        } else {
            String s = null;
            try {
                s = userManageService.createDeptUserExcel(excelFile.getInputStream(), name);
            } catch (UserExistException ue) {
                return "【" + ue.getMessage() + "】该用户名其他单位已存在，请修改用户名";
            } catch (Exception e) {
                return e.getMessage();
            }
            if ("200".equals(s)) {
                return "导入Excel成功";
            } else {
                return s;
            }
        }
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete/{id}")
    public Message delete(@PathVariable List<String> id) {
        boolean del = id.remove(UserUtils.getUserId());
        boolean wrong = false;
        SysUser sysUser = sysUserService.getById(UserUtils.getUserId());
        for (String s : id) {
            SysUser byId = sysUserService.getById(s);
            if ("1".equals(byId.getDemo())) {
                wrong = id.remove(byId.getSysId());
            }
        }
        //公共账号可以删除 自己部门的用户  部门用户不能删除其他成员及公共账号
        if (wrong) {
            return coverMessage("500", "对不起，您无删除公共账号权限");
        }
        if (del) {
            return coverMessage("500", "删除成功，但您不能删除自己");
        }
        if (id.size()>0) {
            sysUserService.batchDelete(id);
            return coverMessage("200","删除成功");
        }else{
            return coverMessage("500","删除失败");
        }
    }

    /**
     * 初始化更新用户表界面
     *
     * @param model
     * @param id
     * @return url
     */
//    @RequiresPermissions("modules:sys:user:edit")
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String showEditView(Model model, @PathVariable String id) {
        //根据自己的过滤规则过滤部门，将来可以考虑是否要修改成下拉树
        List<SysDept> depts = sysDeptService.query();
        SysUserDataBean datebean = sysUserService.getUserDataBeanById(id);
        model.addAttribute("datebean", datebean);
        model.addAttribute("depts", depts);
        return getView("form");
    }

    /**
     * 更新用户表操作
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Message update(@ModelAttribute SysUserDataBean datebean) {
        if (StringUtils.isNotBlank(SysUserUtils.getUserId())) {
            try {
                sysUserService.updateUserLogin(datebean);
            } catch (Exception e) {
                return coverMessage("500", e.getMessage());
            }
            return coverMessage("200");
        } else {
            return coverMessage("500");
        }
    }

    /**
     * 下载用户导入模板
     *
     * @param response
     * @param request
     */
    @RequestMapping(value = "/downUserModle")
    public void downUserModle(HttpServletResponse response, HttpServletRequest request) throws FileNotFoundException, UnsupportedEncodingException {
        //下载本地文件
        String fileName = "单位用户信息导入模板.xlsx".toString();
        // 读到流中
        InputStream inStream = new FileInputStream("c:/dc/单位用户信息导入模板.xlsx");// 文件的存放路径
        // 设置输出的格式
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        try {
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 分配菜单方法
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addRoleMenu")
    public String addRoleMenu() {
        String s = roleMenuUtilsService.addRoleMenu();
        return s;
    }



    @ResponseBody
    @RequestMapping(value = "/getroomuser",method = RequestMethod.GET)
    public Message getroomuser(SysDeptRoomFilter filter){
        if("".equals(filter.getRoomId())||null==filter.getRoomId()){
            return coverMessage("500", "科室编码不能为空");
        }
        String roomId = filter.getRoomId();
        List<SysLogin> roomUser = sysLoginService.getRoomUser(roomId);


        return coverMessage("200", "科室返回成功", roomUser);
    }








}
